import { Service , Inject } from "typedi";
import { getRepository,getConnection } from "typeorm";
import {DynamicEntity} from '../entity/DynamicEntity'
import {UserEntity} from '../entity/UserEntity'
import {DynamicInfoEntity} from '../entity/DynamicInfoEntity'
import {TagEntity} from '../entity/TagEntity'
import {DynamicNewsModel} from '../model/DynamicModel';
import { Params } from "routing-controllers";
import json from "koa-json";

@Service()
export class DynamicDao{


    public async getDynamicDao(dynaimc_Page:number,dynamic_Count:number): Promise<any> {

        return await   getRepository(DynamicEntity)
                            .createQueryBuilder("DynamicEntity")
                            .orderBy("DynamicEntity.dynamic_LikeCount", "DESC")
                            .skip(dynaimc_Page*dynamic_Count)
                            .take(dynamic_Count)
                            .leftJoinAndSelect('DynamicEntity.dynamic_User',"UserEntity")
                            .leftJoinAndSelect('DynamicEntity.dynamic_Info','DynamicInfoEntity')
                            .getMany();
    }
    public async getUserDynamicDao(user_Id:number): Promise<any> {

        return await   getRepository(DynamicEntity)
                            .createQueryBuilder("DynamicEntity")
                            .where("dynamicUserUserId = :Id", { Id: user_Id })
                            .leftJoinAndSelect('DynamicEntity.dynamic_User',"UserEntity")
                            .leftJoinAndSelect('DynamicEntity.dynamic_Info','DynamicInfoEntity')
                            .getMany();
    }
    public async getDynamicTagDao(tag_Page:number,tag_Count:number): Promise<any> {

        return await     getRepository(TagEntity)
                            .createQueryBuilder("tag")
                            .orderBy("tag.tag_SubNum", "DESC")
                            .skip(tag_Page*tag_Count)
                            .take(tag_Count)
                            .getMany();
    }
    public async getFollowDynamicDao(user_Id:number): Promise<any> {

        return await   getRepository(DynamicEntity)
                            .createQueryBuilder("DynamicEntity")
                            .where("dynamicUserUserId = :Id", { Id: user_Id })
                            .leftJoinAndSelect('DynamicEntity.dynamic_User',"UserEntity")
                            .leftJoinAndSelect('DynamicEntity.dynamic_Info','DynamicInfoEntity')
                            .getMany();
    }
    
    public async getRecentVisitDao(user_Id:number): Promise<any> {

        return await   getRepository(UserEntity)
                            .createQueryBuilder("user")
                            .where("user_Id = :Id", { Id: user_Id })
                            .select(["user.user_Id", "user.user_NickName", "user.user_HeadImg"])
                            .getOne();
    }

    public async changeLikeDynamic(dynamic_Id:number,isLike:string): Promise<any> {
        return await   getConnection()
        .createQueryBuilder()
        .update(DynamicEntity)
        .where(`dynamic_Id = :id`, { id: dynamic_Id })
        .set({ dynamic_LikeCount:()=>`dynamic_LikeCount  ${isLike == 'true'?'+':'-'} 1`})
        .execute();
    }

    public async changeCollectionDynamic(dynamic_Id:number,isCollection:string): Promise<any> {
        return await   getConnection()
        .createQueryBuilder()
        .update(DynamicEntity)
        .where(`dynamic_Id = :id`, { id: dynamic_Id })
        .set({ dynamic_CollectionCount:()=>`dynamic_CollectionCount  ${isCollection == 'true'?'+':'-'} 1`})
        .execute();
    }
    

    public async searchTag(content:string): Promise<any> {

        return await    getRepository(TagEntity)
        .createQueryBuilder("tag")
        .where("tag.tag_Title LIKE :name", { name: '%'+content+'%' })
        .getMany();
    }

    public async dynamicNew(params:DynamicNewsModel): Promise<any> {
      let value =   await getConnection()
        .createQueryBuilder()
        .insert()
        .into(DynamicEntity)
        .values({
            dynamic_Time:new Date(),
            dynamic_Img:params.dynamic_ImgList?'dynamic/'+params.dynamic_ImgList[0]:undefined,
            dynamic_Introduce:params.dynamic_Introduce,
            dynamicUserUserId:params.user_id,
            dynamic_TagList:params.dynamic_TagList?JSON.stringify(params.dynamic_TagList):undefined
       })
        .execute();
        await  getConnection()
        .createQueryBuilder()
        .update(DynamicEntity)
        .where("dynamic_Id = :id", { id: value.identifiers[0]["dynamic_Id"] })
        .set({ dynamicInfoDynamicInfoId:value.identifiers[0]["dynamic_Id"]})
        .execute();

         await getConnection()
        .createQueryBuilder()
        .insert()
        .into(DynamicInfoEntity)
        .values({
            dynamicInfo_Id:value.identifiers[0]["dynamic_Id"],
            dynamicInfo_ImgList:params.dynamic_ImgList?JSON.stringify(params.dynamic_ImgList.map((e)=>{return 'dynamic/'+e })):undefined,
       })
        .execute();

        return parseInt(value.identifiers[0]["dynamic_Id"]);
    }

    public async getOneTag(tag_name:String): Promise<any> {

        return await    getRepository(TagEntity)
        .createQueryBuilder("tag")
        .where("tag.tag_Title = :name", { name: tag_name })
        .getOne();
    }

    public async getOneDynamic(dynamic_Id:number): Promise<any> {

        return await    getRepository(DynamicEntity)
        .createQueryBuilder("DynamicEntity")
        .where("DynamicEntity.dynamic_Id = :id", { id: dynamic_Id })
        .leftJoinAndSelect('DynamicEntity.dynamic_User',"UserEntity")
        .leftJoinAndSelect('DynamicEntity.dynamic_Info','DynamicInfoEntity')
        .getOne();
    }

    public async setTagDynamic(dynamicList:string,tag_name:String): Promise<any> {

        return await    getConnection()
        .createQueryBuilder()
        .update(TagEntity)
        .where("tag.tag_Title = :name", { name: tag_name })
        .set({ tag_DynamicList:dynamicList})
        .execute();
    }

    public async addWatchTypeDao(dynamic_Id:number){

        return await getConnection()
        .createQueryBuilder()
        .update(DynamicEntity)
        .where("dynamic_Id = :id", { id: dynamic_Id })
        .set({ dynamic_WatchCount:()=>`dynamic_WatchCount  + 1`})
        .execute();
    }
      

}